import { Provide } from '@midwayjs/core';
import { Repository } from 'typeorm';
import { School } from '../../entity/firmware/school.entity';
import { Edgroup } from '../../entity/firmware/edgroup.entity';
import { InjectEntityModel } from '@midwayjs/typeorm';

@Provide()
export class SchoolService {
  @InjectEntityModel(School)
  schoolRepo: Repository<School>;

  @InjectEntityModel(Edgroup)
  edgroupRepo: Repository<Edgroup>;

  // 创建学校
  async createSchool(name: string, photo: string, edgrp_id: number) {
    // 校验教育集团是否存在
    const edgroup = await this.edgroupRepo.findOneBy({ id: edgrp_id });
    if (!edgroup) {
      throw new Error('教育集团不存在');
    }

    // 校验学校名称和照片是否有效
    if (!name || name.trim() === '') {
      throw new Error('学校名称不能为空');
    }

    const school = new School();
    school.name = name.trim();
    school.photo = photo ? photo.trim() : null; // 如果没有传照片，设置为 null
    school.edgroup = edgroup;
    school.deleted = false;

    try {
      return await this.schoolRepo.save(school);
    } catch (error) {
      throw new Error(`创建学校失败: ${error.message}`);
    }
  }

  // 获取所有学校
  async getAllSchools(param) {
    try {
      const { name, id, pageNum, pageSize } = param
      const query = this.schoolRepo.createQueryBuilder('school')
        .leftJoinAndSelect('school.edgroup', 'edgroup') // 关联 edgrp
        .where('school.deleted != :deleted', { deleted: true });
      if (name) {
        query.andWhere('school.name LIKE :name', { name: `%${name}%` });
      }
      // edgroup_id
      if (id) {
        query.andWhere('school.edgrp_id = :edgrp_id', { edgrp_id: id });
      }
      if (pageNum && pageSize) {
        // 添加分页查询
        query.skip((pageNum - 1) * pageSize).take(pageSize);
      }
      // 查询总数 count
      const total = await query.getCount();
      return {
        data: await query.getMany(), // 加载关联的教育集团
        total: total
      }
    } catch (error) {
      throw new Error(`获取学校列表失败: ${error.message}`);
    }
  }

  // 根据 ID 获取单个学校
  async getSchoolById(id: number) {
    try {
      const school = await this.schoolRepo.findOne({
        where: { id },
        relations: ['edgroup'],
      });

      if (!school) {
        throw new Error('学校不存在');
      }

      return school;
    } catch (error) {
      throw new Error(`获取学校信息失败: ${error.message}`);
    }
  }

  // 更新学校
  async updateSchool(id: number, name?: string, photo?: string, edgrp_id?: number) {
    try {
      const school = await this.getSchoolById(id); // 检查学校是否存在
      if (!school) {
        return null; // 如果学校不存在，直接返回 null
      }
      console.log('name1',name)
      console.log('name.trim()', name.trim())
      // 检查名称是否要更新且不为空
    if (name !== undefined && name.trim() !== '') {
      const trimmedName = name.trim();
      // 检查新名称是否与当前名称不同
      if (trimmedName !== school.name) {
        // 检查新名称是否已被其他学校使用
        const existingSchool = await this.schoolRepo.findOne({ 
          where: { name: trimmedName } 
        });
        console.log('existingSchool', existingSchool, id)
        if (existingSchool && existingSchool.id !== id) {
          throw new Error('学校名称已存在，请使用其他名称');
        }
        school.name = trimmedName;
      }
    }


      if (name !== undefined && name.trim() !== '') school.name = name.trim();
      if (photo !== null && photo.trim() !== '') school.photo = photo.trim();
      if (edgrp_id !== undefined) {
        const edgroup = await this.edgroupRepo.findOneBy({ id: edgrp_id });
        if (!edgroup) {
          throw new Error('教育集团不存在');
        }
        school.edgroup = edgroup;
      }

      return await this.schoolRepo.save(school);
    } catch (error) {
      console.log(error)
      throw new Error(`更新学校失败: ${error.message}`);
    }
  }

  // 删除学校
  async deleteSchool(id: number) {
    try {
      const school = await this.getSchoolById(id); // 检查学校是否存在
      school.deleted = true
      await this.schoolRepo.save(school);
      return await this.schoolRepo.save(school);
    } catch (error) {
      throw new Error(`删除学校失败: ${error.message}`);
    }
  }




}
